package com.onLineCar.manages.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.onLineCar.manages.pojo.CarModel;
import com.onLineCar.manages.mapper.CarModelMapper;
import com.onLineCar.manages.pojo.ImageTable;
import com.onLineCar.manages.pojo.request.CarModelRequest;
import com.onLineCar.manages.service.CarModelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onLineCar.manages.service.ImageTableService;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.onLineCar.manages.pojo.imageenum.ImageEnum.CAR_IMAGE;

/**
 * <p>
 * 车型表 服务实现类
 * </p>
 *
 * @author zhucaiyi
 * @since 2023-12-10
 */
@Service
public class CarModelServiceImpl extends ServiceImpl<CarModelMapper, CarModel> implements CarModelService {

    @Resource
    private ImageTableService imageTableService;

    private final static String SPLICT_STRING = ",";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addCarModel(CarModel carModel) {
        this.baseMapper.insert(carModel);
        String[] images = carModel.getImage().split(SPLICT_STRING);
        imageTableService.saveBatch(Arrays.stream(images)
                .map(image -> ImageTable.builder()
                        .imageCode(CAR_IMAGE.imageType)
                        .imageUrl(image)
                        .description(CAR_IMAGE.imageName)
                        .businessId(carModel.getId())
                        .build()).collect(Collectors.toList()));
        return true;
    }

    @Override
    public IPage<CarModel> queryCarModel(CarModelRequest carModelRequest) {
        LambdaQueryWrapper<CarModel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNoneBlank(carModelRequest.getBrand()), CarModel::getBrand, carModelRequest.getBrand());
        lambdaQueryWrapper.like(StringUtils.isNoneBlank(carModelRequest.getModel()), CarModel::getModel, carModelRequest.getModel());
        lambdaQueryWrapper.like(StringUtils.isNoneBlank(carModelRequest.getOperator()), CarModel::getOperator, carModelRequest.getOperator());
        lambdaQueryWrapper.like(StringUtils.isNoneBlank(carModelRequest.getSeats()), CarModel::getSeats, carModelRequest.getSeats());
        Page<CarModel> carModelPage = this.page(new Page<CarModel>(Long.parseLong(carModelRequest.getPageNum()),
                        Long.parseLong(carModelRequest.getPageSize())),
                lambdaQueryWrapper);
        if (!carModelPage.getRecords().isEmpty()){
            List<Integer> list = carModelPage.getRecords().stream()
                    .map(CarModel::getId)
                    .toList();
            LambdaQueryWrapper<ImageTable> imageTableLambdaQueryWrapper = new LambdaQueryWrapper<>();
            imageTableLambdaQueryWrapper.in(ImageTable::getBusinessId, list);
            List<ImageTable> imageTables = imageTableService.list(imageTableLambdaQueryWrapper);
            Map<Integer, String> carIdAndImageUrLMap = imageTables.stream()
                    .filter(image -> image.getImageCode().equals(CAR_IMAGE.imageType))
                    .collect(Collectors.toMap(ImageTable::getBusinessId,
                            ImageTable::getImageUrl,
                            (entity1, entity2) -> entity1 + SPLICT_STRING + entity2
                    ));
            carIdAndImageUrLMap.forEach((key, value) -> carModelPage.getRecords().stream()
                    .filter(carModel -> carModel.getId().equals(key))
                    .forEach(carModel -> {
                        carModel.setImage(value);
                    }));
        }
        return carModelPage;
    }

    @Override
    public CarModel queryCarModelById(Long id) {
        CarModel carModel = this.baseMapper.selectById(id);
        LambdaQueryWrapper<ImageTable> imageTableLambdaQueryWrapper = new LambdaQueryWrapper<>();
        imageTableLambdaQueryWrapper.eq(ImageTable::getBusinessId, id);
        List<ImageTable> imageTables = imageTableService.list(imageTableLambdaQueryWrapper);
        carModel.setImage(StringUtils.join(imageTables.stream()
                .filter(f -> f.getImageCode().equals(CAR_IMAGE.imageType))
                .map(ImageTable::getImageUrl)
                .toList(), SPLICT_STRING));
        return carModel;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean UpdateCarModel(CarModel carModel) {
        imageTableService.deleteImagesByBusinessId(carModel.getId());
        imageTableService.saveBatch(Arrays.stream(carModel.getImage().split(SPLICT_STRING))
                .map(image -> ImageTable.builder()
                        .imageCode(CAR_IMAGE.imageType)
                        .imageUrl(image)
                        .description(CAR_IMAGE.imageName)
                        .businessId(carModel.getId())
                        .build()).collect(Collectors.toList()));
        this.baseMapper.updateById(carModel);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteCarModelById(Long id) {
        imageTableService.deleteImagesByBusinessId(Integer.parseInt(id.toString()));
        this.baseMapper.deleteById(id);
        return true;
    }
}
